package com.cxf.windex.rest;

import com.cxf.windex.base.msg.ObjectRestResponse;
import com.cxf.windex.base.rest.BaseRestController;
import com.cxf.windex.biz.JsTechBiz;
import com.cxf.windex.entity.JsTech;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.time.LocalDate;

/**
 * @author chenxf
 * @date 3/16/2018
 * @description
 */
@Api(tags = {"小程序 - 点赞接口"})
@Controller
@RequestMapping("/user/like")
public class LikeController extends BaseRestController<JsTechBiz, JsTech> {

  private final int TIMES=1;
  private final String cacheName="LIKEJS";

  @ApiOperation(value = "点赞", notes = "点接赞口，一天只能点赞1次")
  @ApiImplicitParams({
      @ApiImplicitParam(name = "jsId", value = "受赞技师", required = false, paramType = "query", dataType = "String")
  })
  @RequestMapping(value = "/like", method = RequestMethod.GET)
  @ResponseBody
  public ObjectRestResponse edit(String jsId) {
    if(StringUtils.isBlank(jsId)){
      return new ObjectRestResponse().rel(false).msg("请选择点赞技师");
    }
    JsTech entity=new JsTech();
    entity.setId(jsId);
    JsTech tech= baseBiz.selectOne(entity);
    if(tech==null){
      return new ObjectRestResponse().rel(false).msg("找不到ID为"+jsId+"的技师");
    }
    String userId=this.getCurrentUserId();
    if (userId==null) {
      return new ObjectRestResponse().rel(false).msg("无法获取用户信息");
    }
    if(userId.equals(""+tech.getUserid())){
      return new ObjectRestResponse().rel(false).msg("不能给自己点赞");
    }
    LocalDate times=cacheManager.getCache(cacheName).get(userId + jsId,LocalDate.class);
    if (times==null) {

      addLikes(tech);
      cacheManager.getCache(cacheName).put(userId + jsId,
          LocalDate.now());
      return new ObjectRestResponse().rel(true).msg("点赞成功");

    }
    if(LocalDate.now().isAfter(times.plusDays(1))){
      addLikes(tech);
      cacheManager.getCache(cacheName).put(userId + jsId,
          LocalDate.now());
      return new ObjectRestResponse().rel(true).msg("点赞成功");
    }

    return new ObjectRestResponse().rel(false).msg("一天对同一用户只能点赞"+TIMES+"次");
  }

  private void addLikes( JsTech tech){
    JsTech entity=new JsTech();
    entity.setId(tech.getId());
    entity.setScore(tech.getScore()+1);
    baseBiz.updateSelectiveById(entity);
  }
}
